/*
 * @Description:
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-10-20 22:34:11
 */
/**
 * Description:
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/08/19
 * Time: 10:33
 */

package models

import (
	"time"

	"github.com/astaxie/beego/validation"
)

// Article 字段
type Article struct {
	Id          int       `gorm:"primaryKey" json:"id" form:"id"`
	Title       string    `valid:"Required;" json:"title" form:"title"`           // 不能为空
	CategoryId  int       `valid:"Required;" json:"categoryId" form:"categoryId"` // 不能为空
	Slug        string    `json:"slug" form:"slug"`
	Author      string    `json:"author" form:"author"`
	Content     string    `valid:"Required;" json:"content" form:"content"`          // 不能为空
	Markdown    string    `valid:"Required;" json:"markdown" form:"markdown"`        // 不能为空
	Description string    `valid:"Required;"  json:"description" form:"description"` // 不能为空
	Keywords    string    `json:"keywords" form:"keywords"`
	Cover       string    `json:"cover" form:"cover"`
	IsTop       int       `json:"isTop" form:"isTop"`
	Click       int       `json:"click" form:"click"`
	Status      int       `json:"status" form:"status"`
	CreatedAt   time.Time `json:"createdAt" form:"createdAt"`
	UpdatedAt   time.Time `json:"updatedAt" form:"updatedAt"`
}

// TableName 表名
func (a *Article) TableName() string {
	return TableName("articles")
}

// 自定义验证规则
func (m *Article) SelfValid() (msg interface{}) {
	var model Article
	info := map[string]interface{}{}
	valid := validation.Validation{}
	if b, _ := valid.Valid(m); !b {
		for _, err := range valid.Errors {
			return err.Message
		}
	}
	if m.Id != 0 {
		Db.Model(&model).Where("title = ?", m.Title).Where("id <> ?", m.Id).Find(&info)
	} else {
		Db.Model(&model).Where("title = ?", m.Title).Find(&info)
	}
	// Name 唯一
	if len(info) > 0 {
		return "标题唯一，不能重复"
	}
	return nil
}
